package Client;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Hashtable;

public final class GameInterface {
    private static Hashtable<Integer, GameInterface> interfaceCache = new Hashtable<Integer, GameInterface>();
    private int[] sprites;
    private int[][] spriteCoords;
    private boolean[] spriteIsButton;
    private String[] text;
    private int[][] textCoords;
    private boolean[] textIsButton;

    public GameInterface(ByteStream stream) {
        int spriteCount = stream.getSmart();
        sprites = new int[spriteCount];
        spriteCoords = new int[spriteCount][];
        spriteIsButton = new boolean[spriteCount];
        for (int i = 0; i < spriteCount; i++) {
            sprites[i] = stream.getUnsignedShort();
            spriteCoords[i] = new int[] { stream.getSmart(), stream.getSmart() };
            spriteIsButton[i] = stream.getUnsignedByte() == 1;
        }
        int textCount = stream.getSmart();
        text = new String[textCount];
        textCoords = new int[textCount][];
        textIsButton = new boolean[textCount];
        for (int i = 0; i < textCount; i++) {
            text[i] = stream.getString();
            textCoords[i] = new int[] { stream.getSmart(), stream.getSmart() };
            textIsButton[i] = stream.getUnsignedByte() == 1;
        }
    }

    public int[] sprites() {
        return sprites;
    }

    public int[][] spriteCoords() {
        return spriteCoords;
    }

    public String[] text() {
        return text;
    }

    public int[][] textCoords() {
        return textCoords;
    }

    public static GameInterface getInterface(int id) {
        if (interfaceCache.containsKey(id)) {
            return interfaceCache.get(id);
        }
        ByteStream stream;
        try {
            File f = new File("./cache/interfaces/" + id + ".dat");
            stream = new ByteStream((int) f.length());
            stream.setLength((int) f.length());
            FileInputStream in = new FileInputStream(f);
            in.read(stream.buffer(), 0, (int) f.length());
            in.close();
        } catch (IOException ioe) {
            return null;
        }
        GameInterface gi = new GameInterface(stream);
        interfaceCache.put(id, gi);
        return gi;
    }
}